const {
  override,
  addWebpackAlias,
  disableEsLint,
  overrideDevServer,
  adjustStyleLoaders
} = require('customize-cra')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const path = require('path')

const isBuild = process.env.NODE_ENV === 'production' // 打包
const isProduction = process.env.REACT_APP_ENV === 'production' // 打包环境
const isTest = process.env.REACT_APP_ENV === 'test' // 打包环境

function resolve(dir) {
  return path.join(__dirname, dir)
}

/* 进度条提示 */
const progressBarPlugin = require('progress-bar-webpack-plugin')({
  width: 60,
  format: `running: :percent`,
  clear: true,
})

/* 生产环境下的插件 */
const prodPlugins = [
  new UglifyJsPlugin({ // 去除console和debug
    uglifyOptions: {
      warnings: false,
      compress: {
        drop_debugger: true,
        drop_console: true
      }
    }
  })
]

/* 开发环境，初始化环境变量 */
if (!isBuild) {
  process.env.PORT = '3000'
  process.env.HTTPS = true
  process.env.HOST = '0.0.0.0'
}

module.exports = {
  paths: (path) => {
    path.appBuild = resolve('./dist')
    return path
  },
  webpack: override(
    // 路径别名
    addWebpackAlias({
      '@': path.resolve(__dirname, 'src'),
    }),
    adjustStyleLoaders(rule => {
      if (rule.test.toString().includes('scss')) {
        rule.use.push({
          loader: require.resolve('sass-resources-loader'),
          options: {
            resources: [
              './src/styles/variable.scss',
            ]
          }
        })
      }
    }),
    // 忽略eslint警告
    disableEsLint(),
    (config) => {
      if (isBuild) {
        config.devtool = false // 取消map文件
        config.plugins.push(progressBarPlugin)

        if (isProduction) {
          config.plugins = config.plugins.concat(prodPlugins)
        }
      }

      return config
    }
  ),
  devServer: overrideDevServer(config => {
    return {
      ...config,
    }
  })
}
